﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Application.Common.Interfaces;
using AutoMapper;
using Common.Attributes;
using Common.Enums;
using Common.Services;
using Domain.Entities;
using Domain.Entities.Identity;
using MediatR;

namespace Application.Features.Users.Commands.Add;

/// <summary>
/// 创建用户
/// </summary>
[Map(typeof(User))]
[Description("创建")]
[GroupDescription(("用户管理"))]
public class AddUserCommand : IRequest<bool>
{
    /// <summary>
    /// 用户名
    /// </summary>
    [Required(ErrorMessage = "用户名是必填的")]
    public string UserName { get; set; }

    /// <summary>
    /// 真实姓名
    /// </summary>
    [Description("真实姓名")]
    public  string? Realname { get; set; }

    /// <summary>
    /// 昵称
    /// </summary>
    [Description("昵称")]
    public  string? Nickname { get; set; }

    /// <summary>
    /// 性别
    /// </summary>
    [Description("性别")]
    public GenderType GenderType { get; set; }

    /// <summary>
    /// 个性签名
    /// </summary>
    [Description("个性签名")]
    public string? Signature { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [Required(ErrorMessage = "密码是必填的")]
    public string Password { get; set; }

    /// <summary>
    /// 确认密码
    /// </summary>
    [Required(ErrorMessage = "确认密码是必填的")]
    public string ConfirmPassword { get; set; }

    /// <summary>
    /// 邮箱
    /// </summary>
    public string? Email { get; set; }

    /// <summary>
    /// 手机号码
    /// </summary>
    public string? PhoneNumber { get; set; }

    /// <summary>
    /// 用户状态：是否激活
    /// </summary>
    [Required(ErrorMessage = "用户状态是必填的")]
    public bool IsActive { get; set; }

    /// <summary>
    /// 上级节点
    /// </summary>
    public long? ParentId { get; set; }

    /// <summary>
    /// 组织机构唯一标识
    /// </summary>
    public long? OrganizationId { get; set; }

}

/// <summary>
/// 处理程序
/// </summary>
public class AddUserCommandHandler : IRequestHandler<AddUserCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly ISnowFlakeService _snowFlakeService;
    private readonly IMapper _mapper;

    public AddUserCommandHandler(
        IApplicationDbContext context,
        IMapper mapper,
        ISnowFlakeService snowFlakeService)
    {
        _context = context;
        _mapper = mapper;
        _snowFlakeService = snowFlakeService;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(AddUserCommand request, CancellationToken cancellationToken)
    {
        var user = _mapper.Map<User>(request);
        user.PasswordHash = user.CreatePassword(request.Password);
        await _context.Users.AddAsync(user);

        return true;
    }
}
